package au.com.bus4u.controller.admin;


import au.com.bus4u.controller.BaseController;
import au.com.bus4u.exception.ServiceException;
import au.com.bus4u.service.UserService;
import au.com.bus4u.utils.CodeUtil;
import au.com.bus4u.utils.JsonResult;
import au.com.bus4u.utils.PageData;
import lombok.extern.java.Log;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@Log
public class AdminController extends BaseController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserService userService;


    @ResponseBody
    @RequestMapping("/login")
    public JsonResult<Map> login(String phone, String password, String code)throws Exception{
        log.info("=========================================");
        //System.out.println("user_email = [" + user_email + "], password = [" + password + "], code = [" + code + "]");
        PageData requestPD = getPageData();
        HttpSession session = request.getSession();
        Map<String, Object> result = new HashMap<>();
//        System.err.println("浏览器请求来的session中的验证码为:"+session.getAttribute("code"));
        if( session.getAttribute("code") == null) throw new ServiceException("验证码已过期,请重新输入新的验证码！");

//        System.err.println(session.getAttribute("code").toString().equalsIgnoreCase(code));
        //对比 验证码
        if(!session.getAttribute("code").toString().equalsIgnoreCase(code)) throw new ServiceException("Code incorrect!");

//        System.err.println(session.getAttribute("code"));

        List<PageData> byPhone = userService.findByPhone(phone);
        PageData currentUser = null;
        String salt = "";
        if(byPhone.size()>0){
            currentUser = byPhone.get(0);
            salt = currentUser.get("salt").toString();
        }
        Subject subject = SecurityUtils.getSubject();
//        System.err.println("原始密码："+password);
//        System.err.println("加密密码："+getMd5Password(password,salt));
        UsernamePasswordToken token = new UsernamePasswordToken(phone,getMd5Password(password,salt));
//        UsernamePasswordToken token = new UsernamePasswordToken(phone,password);

        subject.login(token);//执行shiro的登陆

        //移除Session中不要的用户的数据
        currentUser.remove("password");
        currentUser.remove("salt");
        currentUser.remove("create_time");
        currentUser.remove("create_ip");
        currentUser.remove("update_time");
        currentUser.remove("last_login_time");
        currentUser.remove("last_login_ip");

        //判断用户角色 返回对应角色附加数据
        int role_id = Integer.parseInt(currentUser.get("role_id").toString());
        switch(role_id) {
            case 1:
                //SuperAdmin-超级管理员;
                break;
            case 2:
                //Admin-管理员;
                break;
            case 3:
                //Carrier-承运商;
                PageData carrier = userService.findCarrierByUserID(currentUser.get("user_id").toString());
                currentUser.put("carrier",carrier);
                break;
            case 4:
                //Driver-司机;
                PageData driver = userService.findDriverByUserID(currentUser.get("user_id").toString());
                currentUser.put("driver",driver);
                break;
//            case 5:
//                //Guest-游客;
//                PageData guest = userService.findGuestByUserID(currentUser.get("user_id").toString());
//                currentUser.put("guest",guest);
//                break;
            default:
                //...;
                break;
        }
        //把当前用户信息存到session中(包含对应角色附加数据)
//        System.err.println("currentUser:"+currentUser);
        SecurityUtils.getSubject().getSession().setAttribute("currentUser", currentUser);

        //保存最后次登陆时间、IP
        PageData lastLogin = new PageData();
        lastLogin.put("user_id",currentUser.get("user_id"));
        lastLogin.put("role_id",currentUser.get("role_id"));
        lastLogin.put("last_login_time",new Date());
        lastLogin.put("last_login_ip",requestPD.getIpAddress());
        userService.edit(lastLogin);//登陆成功 执行保存最后次登陆时间和最后次登陆IP

        return new JsonResult<Map>(SUCCESS, result);
    }

    @ResponseBody
    @RequestMapping("/regist")
    public JsonResult<Map> regist()throws Exception{
        log.info("=========================================");
        Map<String, Object> result = new HashMap<>();
        PageData pageData = getPageData();
//        System.err.println("UserController.regist");
//        System.err.println("pageData = " + pageData);

        userService.save(pageData);

        return new JsonResult<Map>(SUCCESS, result);
    }

    /**
     * @修改用户信息
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/update")
    public JsonResult<Map> update()throws Exception{
        log.info("=========================================");
        Map<String, Object> result = new HashMap<>();
        PageData pageData = getPageData();
//        System.err.println("pageData = " + pageData);

        userService.edit(pageData);

        updataSessionUser();//更新sesssion中的当前登录用户数据
        return new JsonResult<Map>(SUCCESS, result);
    }












    /**
     * 后台产生验证码
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/getCode")
    public void getCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        log.info("=========================================");
        // 调用工具类生成的验证码和验证码图片
        Map<String, Object> codeMap = CodeUtil.generateCodeAndPic();

        // 将四位数字的验证码保存到Session中。
        HttpSession session = req.getSession();
        String code = codeMap.get("code").toString();
        session.setAttribute("code",code);
//        System.err.println("服务器验证码:"+code);
        // 禁止图像缓存。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", -1);
        resp.setContentType("image/jpeg");

        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos;
        try
        {
            sos = resp.getOutputStream();
            ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
            sos.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }


    /**
     * 	 对密码进行加密
     * @param password 原始密码
     * @param salt 盐值
     * @return 加密后的密码
     */
    private static String getMd5Password(String password,String salt) {
        // salt+password+salt 进行3次加密
        String msg=salt+password+salt;
        for(int i=0;i<3;i++) {
            msg= DigestUtils.md5DigestAsHex(msg.getBytes());
        }
        return msg;
    }


    private void updataSessionUser() throws Exception {
//        System.err.println("UserController.updataSessionUser");
        String currentUserID = getCurrentUserID();
        PageData currentUser = userService.findById(currentUserID);

                //移除Session中不要的用户的数据
        currentUser.remove("password");
        currentUser.remove("salt");
        currentUser.remove("create_time");
        currentUser.remove("create_ip");
        currentUser.remove("update_time");
        currentUser.remove("last_login_time");
        currentUser.remove("last_login_ip");

        //判断用户角色 返回对应角色附加数据
        int role_id = Integer.parseInt(currentUser.get("role_id").toString());
        switch(role_id) {
            case 1:
                //SuperAdmin-超级管理员;
                break;
            case 2:
                //Admin-管理员;
                break;
            case 3:
                //Carrier-承运商;
                PageData carrier = userService.findCarrierByUserID(currentUser.get("user_id").toString());
                currentUser.put("carrier",carrier);
                break;
            case 4:
                //Driver-司机;
                PageData driver = userService.findDriverByUserID(currentUser.get("user_id").toString());
                currentUser.put("driver",driver);
                break;
//            case 5:
//                //Guest-游客;
//                PageData guest = userService.findGuestByUserID(currentUser.get("user_id").toString());
//                currentUser.put("guest",guest);
//                break;
            default:
                //...;
                break;
        }
        //把当前用户信息存到session中(包含对应角色附加数据)
//        System.err.println("currentUser:"+currentUser);
        SecurityUtils.getSubject().getSession().setAttribute("currentUser", currentUser);
    }
}
